﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Pur;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.Bpt;
using ESOL.WinUI.Sales;
using ESOL.WinUI.Hr;

namespace ESOL.WinUI.Pur
{
    public partial class frmMaintainPurchaseQuoteOrder : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public PurQuoteOrderEntity SelectedPurQuoteOrder { get; set; }
        private List<PurQuoteItemEntity> DeleteList = new List<PurQuoteItemEntity>();

        private PurPurchaseOrderEntity mPurPurchaseOrder;
        #endregion

        #region Constructor
        public frmMaintainPurchaseQuoteOrder()
        {
            InitializeComponent();
            if (SelectedPurQuoteOrder == null)
            {
                SelectedPurQuoteOrder = new PurQuoteOrderEntity();
                SelectedPurQuoteOrder.QuoteOrderId = Guid.NewGuid().ToString();
            }
        }

        public frmMaintainPurchaseQuoteOrder(PurPurchaseOrderEntity entity, MstSupplierEntity supplier)
        {
            InitializeComponent();
            if (SelectedPurQuoteOrder == null)
            {
                SelectedPurQuoteOrder = new PurQuoteOrderEntity();
                SelectedPurQuoteOrder.QuoteOrderId = Guid.NewGuid().ToString();
            }

            SetFieldsBySupplier(supplier);
            SetFieldsByPurOrder(entity, true);
        }
        #endregion

        #region Functions
        private void InitializaFields()
        {
            MstCustomerEntity customer = MstCustomerBs.GetMstCustomerByCode(CommonParameter.MyCompanyCode);
            if (customer != null)
            {
                txtCustomer.Text = customer.CustomerName;
                txtCustomer.Tag = customer;
                MstCustomerContactEntity contact = UICommonFunctions.GetMainCustomerContact(customer.CustomerId);
                if (contact != null)
                {
                    txtCustomerContact.Text = contact.ContactName;
                    txtCustomerContactPhone.Text = contact.ContactMobilephone;
                }
            }
        }

        private void SetFieldsBySupplier(MstSupplierEntity supplier)
        {
            if (supplier != null)
            {
                txtSupplier.Tag = supplier;
                txtSupplier.Text = supplier.SupplierName;
                MstSupplierContactEntity contact = UICommonFunctions.GetMainSupplierContact(supplier.SupplierId);
                if (contact != null)
                {
                    txtSupplierContact.Text = contact.ContactName;
                    txtSupplierContactPhone.Text = contact.ContactMobilephone;
                }
            }
            else
            {
                if (supplier != null)
                {
                    txtSupplier.Tag = null;
                    txtSupplier.Text = "";
                    txtSupplierContact.Text = "";
                    txtSupplierContactPhone.Text = "";
                }
            }
        }

        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbCurrency, "CS", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "STATUS", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPaymentType, "PAYWAY", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colUNIT, "UNIT", true);
        }

        private void BindDataGridDetail()
        {
            string quoteOrderId = "";
            if (SelectedPurQuoteOrder != null)
            {
                quoteOrderId = SelectedPurQuoteOrder.QuoteOrderId;
            }
            DataSet ds = PurQuoteItemBs.GetDataSetByQuoteOrderID(quoteOrderId);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvMain.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            dt.AcceptChanges();
            gvMain.DataSource = dt;
            DeleteList = new List<PurQuoteItemEntity>();
        }

        private void SetDataGridDetailByPurchaseOrder()
        {
            if (mPurPurchaseOrder == null)
            {
                return;
            }
            if (gvMain.DataSource == null)
            {
                BindDataGridDetail();
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            List<PurPurchaseOrderItemEntity> list = PurPurchaseOrderItemBs.GetByPurchaseOrderID(mPurPurchaseOrder.PurchaseOrderId);
            foreach (PurPurchaseOrderItemEntity entity in list)
            {
                DataRow dr = dt.NewRow();
                dr["QUOTE_ITEM_ID"] = Guid.NewGuid().ToString();
                dr["QUOTE_ORDER_ID"] = SelectedPurQuoteOrder.QuoteOrderId;
                dr["PURCHASE_ITEM_ID"] = entity.PurchaseItemId;
                MstProductEntity product = MstProductBs.GetMstProductTypeByID(entity.ProductId);
                if (product != null)
                {
                    dr["PRODUCT_ID"] = product.ProductId;
                    dr["PRODUCT_CODE"] = product.ProductCode;
                    dr["PRODUCT_NAME"] = product.ProductName;
                    dr["PRODUCT_SPEC_IN"] = product.ProductSpecIn;
                    dr["MATERIAL"] = product.Material;
                    dr["UNIT"] = product.Unit;
                    dr["DESCRIPTION"] = product.Description;
                }
                dr["QTY"] = entity.Qty;
                dr["TAX_RATE"] = 0.17;
                dr["PRICE_NO_TAX"] = decimal.Round(entity.PriceNoTax, 2);
                dr["TOTAL_AMOUNT"] = decimal.Round(entity.PriceNoTax * entity.Qty, 2);
                dt.Rows.Add(dr);
            }
            ResetTotalAmount();
        }

        private void ResetTax()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            decimal totalAmount = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["TOTAL_AMOUNT"] != null && CommonFunctions.IsDecimal(dr["TOTAL_AMOUNT"].ToString()))
                {
                    decimal tax = CommonFunctions.ToDecimal(dr["TAX_RATE"]) + 1;
                    decimal price = CommonFunctions.ToDecimal(dr["PRICE_NO_TAX"]);
                    if (cboxIsTax.Checked)
                    {
                        price = price * tax;
                    }
                    else
                    {
                        price = price / tax;
                    }
                    decimal amount = CommonFunctions.ToDecimal(dr["QTY"]) * price;
                    dr["PRICE_NO_TAX"] = price.ToString("#0.00");
                    dr["TOTAL_AMOUNT"] = amount.ToString("#0.00");
                    totalAmount += amount;
                }
            }
        }

        private void ResetTotalAmount()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            decimal totalAmount = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (string.IsNullOrEmpty(dr["PRICE_NO_TAX"].ToString()) == false &&
                    string.IsNullOrEmpty(dr["QTY"].ToString()) == false)
                {
                    decimal qty = Convert.ToDecimal(dr["QTY"].ToString());
                    decimal price = Convert.ToDecimal(dr["PRICE_NO_TAX"].ToString());
                    totalAmount += qty * price;
                }
            }
            txtTotalAmount.Text = decimal.Round(totalAmount, 2).ToString();
        }

        private void SetFieldsByPurOrder(PurPurchaseOrderEntity purOrder, bool setDetail)
        {
            mPurPurchaseOrder = purOrder;
            if (mPurPurchaseOrder != null)
            {
                txtPurchaseOrder.Tag = mPurPurchaseOrder;
                txtPurchaseOrder.Text = mPurPurchaseOrder.PurchaseOrderCode;
                if (setDetail)
                {
                    //Set Detail
                    if (gvMain.DataSource != null)
                    {
                        DataTable dt = gvMain.DataSource as DataTable;
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (dr.RowState != DataRowState.Added)
                            {
                                PurQuoteItemEntity entity = new PurQuoteItemEntity(dr);
                                DeleteList.Add(entity);
                            }
                        }
                    }
                    SetDataGridDetailByPurchaseOrder();
                }
            }
        }

        private void SetFields()
        {
            BindDataGridDetail();
            if (SelectedPurQuoteOrder == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(SelectedPurQuoteOrder.SupplierId) == false)
            {
                MstSupplierEntity supplier = MstSupplierBs.GetMstSupplierById(SelectedPurQuoteOrder.SupplierId);
                if (supplier != null)
                {
                    SetFieldsBySupplier(supplier);
                }
            }
            txtQuoteOrderCode.Text = SelectedPurQuoteOrder.QuoteOrderCode;
            if (string.IsNullOrEmpty(txtQuoteOrderCode.Text))
            {
                txtQuoteOrderCode.Text = "自动生成";
            }
            mPurPurchaseOrder = PurPurchaseOrderBs.GetPurchaseOrderByID(SelectedPurQuoteOrder.PurchaseOrderId);
            SetFieldsByPurOrder(mPurPurchaseOrder, false);
            if (ThisActionType == ActionType.New)
            {
                MstPersonEntity person = MstPersonBs.GetMstPersonByID(CommonParameter.CurrentUser.PersonId);
                if (person != null)
                {
                    txtQuotePerson.Tag = person;
                    txtQuotePerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                }
            }
            else
            {
                if (string.IsNullOrEmpty(SelectedPurQuoteOrder.QuotePerson) == false)
                {
                    MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedPurQuoteOrder.QuotePerson);
                    if (person != null)
                    {
                        txtQuotePerson.Tag = person;
                        txtQuotePerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                    }
                }
            }
            txtTotalAmount.Text = SelectedPurQuoteOrder.QuoteTotalAmount.ToString();
            cmbCurrency.SetSelectedValue(SelectedPurQuoteOrder.Currency);
            cmbPaymentType.SetSelectedValue(SelectedPurQuoteOrder.PaymentType);
            if (SelectedPurQuoteOrder.IsTax == 1)
            {
                cboxIsTax.Checked = true;
            }
            else
            {
                cboxIsTax.Checked = false;
            }
            dtpDeliveryRequiredDate.EditValue = SelectedPurQuoteOrder.DeliveryRequiredDate;
            dtpDeliveryPlanDate.EditValue = SelectedPurQuoteOrder.DeliveryPlanDate;
            dtpQuoteDate.EditValue = SelectedPurQuoteOrder.QuoteDate;
            dtpExpiredDate.EditValue = SelectedPurQuoteOrder.QuoteExpiredDate;
            cmbStatus.SetSelectedValue(SelectedPurQuoteOrder.Status);
            txtRemark.Text = SelectedPurQuoteOrder.Remark;

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, SelectedPurQuoteOrder.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, SelectedPurQuoteOrder.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, SelectedPurQuoteOrder.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, SelectedPurQuoteOrder.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedPurQuoteOrder.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, SelectedPurQuoteOrder.ApprovedBy);
        }

        private void SetEntity()
        {
            if (txtSupplier.Tag != null && txtSupplier.Tag.GetType() == typeof(MstSupplierEntity))
            {
                SelectedPurQuoteOrder.SupplierId = ((MstSupplierEntity)txtSupplier.Tag).SupplierId;
            }
            if (txtQuotePerson.Tag != null && txtQuotePerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                SelectedPurQuoteOrder.QuotePerson = ((MstPersonEntity)txtQuotePerson.Tag).PersonId;
                SelectedPurQuoteOrder.QuoteDepartment = ((MstPersonEntity)txtQuotePerson.Tag).DepartmentId;
            }
            if (txtPurchaseOrder.Tag != null && txtPurchaseOrder.Tag.GetType() == typeof(PurPurchaseOrderEntity))
            {
                SelectedPurQuoteOrder.PurchaseOrderId = ((PurPurchaseOrderEntity)txtPurchaseOrder.Tag).PurchaseOrderId;
            }
            SelectedPurQuoteOrder.QuoteTotalAmount = CommonFunctions.ToDecimal(txtTotalAmount.Text);
            if (cmbCurrency.SelectedValue != null && cmbCurrency.SelectedValue.ToString().Trim() != "")
            {
                SelectedPurQuoteOrder.Currency = cmbCurrency.SelectedValue.ToString().Trim();
            }
            if (cmbPaymentType.SelectedValue != null && cmbPaymentType.SelectedValue.ToString().Trim() != "")
            {
                SelectedPurQuoteOrder.PaymentType = cmbPaymentType.SelectedValue.ToString().Trim();
            }
            if (cboxIsTax.Checked)
            {
                SelectedPurQuoteOrder.IsTax = 1;
            }
            else
            {
                SelectedPurQuoteOrder.IsTax = 0;
            }
            if (dtpDeliveryRequiredDate.EditValue!=null)
            {
                SelectedPurQuoteOrder.DeliveryRequiredDate = Convert.ToDateTime(dtpDeliveryRequiredDate.EditValue);
            }
            if (dtpQuoteDate.EditValue != null)
            {
                SelectedPurQuoteOrder.QuoteDate = Convert.ToDateTime(dtpQuoteDate.EditValue);
            }
            if (dtpExpiredDate.EditValue != null)
            {
                SelectedPurQuoteOrder.QuoteExpiredDate = Convert.ToDateTime(dtpExpiredDate.EditValue);
            }
            if (dtpDeliveryPlanDate.EditValue != null)
            {
                SelectedPurQuoteOrder.DeliveryPlanDate = Convert.ToDateTime(dtpDeliveryPlanDate.EditValue);
            }
            if (dtpExpiredDate.EditValue != null)
            {
                SelectedPurQuoteOrder.QuoteExpiredDate = Convert.ToDateTime(dtpExpiredDate.EditValue);
            }
            SelectedPurQuoteOrder.Status = NormalStatus.STATUS02.ToString();
            SelectedPurQuoteOrder.Remark = txtRemark.Text;

            if (ThisActionType == ActionType.New)
            {
                SelectedPurQuoteOrder.CreatedDate = DateTime.Now;
                SelectedPurQuoteOrder.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedPurQuoteOrder.LastModifiedDate = DateTime.Now;
                SelectedPurQuoteOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }

        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtSupplier.Text))
            {
                MessageBox.Show("供应商不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtCustomer.Text))
            {
                MessageBox.Show("客户不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtQuotePerson.Text))
            {
                MessageBox.Show("询价人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbCurrency.SelectedValue == null || cmbCurrency.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("货币种类不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpQuoteDate.EditValue == null)
            {
                MessageBox.Show("报价日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (gvMain.DataSource == null)
            {
                MessageBox.Show("询价明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("询价明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = PurQuoteOrderBs.SaveQuoteOrder(true, SelectedPurQuoteOrder, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = PurQuoteOrderBs.SaveQuoteOrder(false, SelectedPurQuoteOrder, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SelectedPurQuoteOrder.ApprovedDate = DateTime.Now;
                    SelectedPurQuoteOrder.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    bool isSuccessful = PurQuoteOrderBs.UpdatePurQuoteOrder(SelectedPurQuoteOrder);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private bool UploadAttached(string fileFullName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileFullName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        SelectedPurQuoteOrder.AttachedFile = SelectedPurQuoteOrder.QuoteOrderCode + "." + CommonFunctions.GetFileExtension(fileFullName);
                        string path = service.PurchaseQuoteAttachedPath();
                        byte[] bytes = CommonFunctions.FileToByte(fileFullName);
                        string errMsg = "";
                        bool result = service.UploadFileNew(bytes, path + "\\" + SelectedPurQuoteOrder.AttachedFile, out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        result = PurQuoteOrderBs.UpdatePurQuoteOrder(SelectedPurQuoteOrder);
                        if (result)
                        {
                            txtAttached.Text = SelectedPurQuoteOrder.AttachedFile;
                        }
                        return result;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private bool DownloadAttached(string fileFullName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileFullName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        string errMsg = "";
                        string path = service.PurchaseQuoteAttachedPath();
                        byte[] bytes = service.DownloadFileNew(path + "\\" + SelectedPurQuoteOrder.AttachedFile, out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        Image image = CommonFunctions.byteArrayToImage(bytes);
                        image.Save(fileFullName);
                        image.Dispose();
                        return true;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            InitializaFields();
            BindComboBox();
            if (ThisActionType != ActionType.New)
            {
                SetFields();
            }
            base.OnShown(e);
        }

        DataRow drItemSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drItemSelected = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        private void cboxIsTax_CheckedChanged(object sender, EventArgs e)
        {
            if (cboxIsTax.Checked)
            {
                gridView1.Columns["PRICE_NO_TAX"].Caption = "单价（含税）";
                gridView1.Columns["TOTAL_AMOUNT"].Caption = "小计（含税）";

            }
            else
            {
                gridView1.Columns["PRICE_NO_TAX"].Caption = "单价";
                gridView1.Columns["TOTAL_AMOUNT"].Caption = "小计";
            }
            ResetTax();
            ResetTotalAmount();
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (drItemSelected == null)
            {
                return;
            }
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                drItemSelected["PRODUCT_ID"] = frm.SelectedProduct.ProductId;
                drItemSelected["PRODUCT_CODE"] = frm.SelectedProduct.ProductCode;
                drItemSelected["PRODUCT_NAME"] = frm.SelectedProduct.ProductName;
                drItemSelected["PRODUCT_SPEC_IN"] = frm.SelectedProduct.ProductSpecIn;
                drItemSelected["MATERIAL"] = frm.SelectedProduct.Material;
                drItemSelected["UNIT"] = frm.SelectedProduct.Unit;
            }
        }

        private void txtSupplier_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainSupplierQuery frm = new frmMaintainSupplierQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedSupplier != null)
            {
                txtSupplier.Text = frm.SelectedSupplier.SupplierName;
                txtSupplier.Tag = frm.SelectedSupplier;

                MstSupplierContactEntity contact = UICommonFunctions.GetMainSupplierContact(frm.SelectedSupplier.SupplierId);
                if (contact != null)
                {
                    txtSupplierContact.Text = contact.ContactName;
                    txtSupplierContactPhone.Text = contact.ContactMobilephone;
                }
            }
            else
            {
                txtSupplier.Text = "";
                txtSupplier.Tag = null;

                txtSupplierContact.Text = "";
                txtSupplierContactPhone.Text = "";
            }
        }

        private void txtCustomer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainCustomerQuery frm = new frmMaintainCustomerQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedCustomer != null)
            {
                txtCustomer.Text = frm.SelectedCustomer.CustomerName;
                txtCustomer.Tag = frm.SelectedCustomer;

                MstCustomerContactEntity contact = UICommonFunctions.GetMainCustomerContact(frm.SelectedCustomer.CustomerId);
                if (contact != null)
                {
                    txtCustomerContact.Text = contact.ContactName;
                    txtCustomerContactPhone.Text = contact.ContactMobilephone;
                }
            }
            else
            {
                txtCustomer.Text = "";
                txtCustomer.Tag = null;

                txtCustomerContact.Text = "";
                txtCustomerContactPhone.Text = "";
            }
        }

        private void txtPurchaseOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainPurchaseOrderQuery frm = new frmMaintainPurchaseOrderQuery(false);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPurchaseOrder != null)
            {
                mPurPurchaseOrder = frm.SelectedPurchaseOrder;
                txtPurchaseOrder.Tag = frm.SelectedPurchaseOrder;
                SetFieldsByPurOrder(frm.SelectedPurchaseOrder, true);
            }
            else
            {
                txtPurchaseOrder.Text = "";
                txtPurchaseOrder.Tag = null;
            }
        }

        private void txtQuotePerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtQuotePerson.Text = frm.SelectedPerson.NameCn;
                txtQuotePerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtQuotePerson.Text = "";
                txtQuotePerson.Tag = null;
            }
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            if (ThisActionType == ActionType.View)
            {
                return;
            }
            if (ThisActionType == ActionType.New || SelectedPurQuoteOrder == null)
            {
                MessageBox.Show("请先保存后再上传文件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            OpenFileDialog fd = new OpenFileDialog();
            fd.Multiselect = false;
            fd.Filter = "JPG文件|*.jpg|PNG文件|*.png";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                bool result = UploadAttached(fd.FileName);
                Cursor = Cursors.Default;
                if (result)
                {
                    MessageBox.Show("上传成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (ThisActionType == ActionType.New)
            {
                MessageBox.Show("没有可下载的附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (string.IsNullOrEmpty(SelectedPurQuoteOrder.AttachedFile))
            {
                MessageBox.Show("没有找到可以下载的附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SaveFileDialog fd = new SaveFileDialog();
            fd.FileName = SelectedPurQuoteOrder.AttachedFile;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                bool result = DownloadAttached(fd.FileName);
                Cursor = Cursors.Default;
                if (result)
                {
                    MessageBox.Show("下载成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedPurQuoteOrder = new PurQuoteOrderEntity();
                SelectedPurQuoteOrder.QuoteOrderId = Guid.NewGuid().ToString();
                SetFields();
            }
        }

        protected override void Click_Approve()
        {
            if (SelectedPurQuoteOrder == null)
            {
                return;
            }
            SelectedPurQuoteOrder.Status = NormalStatus.STATUS03.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_Reject()
        {
            if (SelectedPurQuoteOrder == null)
            {
                return;
            }
            SelectedPurQuoteOrder.Status = NormalStatus.STATUS04.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void tsmNew_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            DataRow dr = dt.NewRow();
            dr["QUOTE_ITEM_ID"] = Guid.NewGuid().ToString();
            dr["QUOTE_ORDER_ID"] = SelectedPurQuoteOrder.QuoteOrderId;
            dr["TAX_RATE"] = 0.17;
            dt.Rows.Add(dr);
        }

        private void tsmDelete_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            if (drItemSelected == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (drItemSelected.RowState != DataRowState.Added)
            {
                PurQuoteItemEntity entity = new PurQuoteItemEntity(drItemSelected);
                DeleteList.Add(entity);
            }
            dt.Rows.Remove(drItemSelected);
            ResetTotalAmount();
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.Equals("QTY") || e.Column.FieldName.Equals("PRICE_NO_TAX"))
            {
                if (string.IsNullOrEmpty(drItemSelected["QTY"].ToString()) ||
                    string.IsNullOrEmpty(drItemSelected["PRICE_NO_TAX"].ToString()))
                {
                    return;
                }
                decimal unitPrice = 0;
                decimal qty = 0;
                unitPrice = Convert.ToDecimal(drItemSelected["PRICE_NO_TAX"].ToString());
                qty = Convert.ToDecimal(drItemSelected["QTY"].ToString());
                drItemSelected["TOTAL_AMOUNT"] = unitPrice * qty;
                ResetTotalAmount();
            }
        }
        #endregion
    }
}
